import java.util.Stack;

public class BinaryTree {
    static class TreeNode{
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }
    public TreeNode root;//指向一个根节点
    public TreeNode createTree(){
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');

        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        C.left = F;
        C.right = G;
        E.right = H;
        return A;
    }

    public void preOrder(TreeNode root){
        if (root == null) {
            return;
        }
        System.out.print(root.val+" ");
        preOrder(root.left);
        preOrder(root.right);
    }

    public void inOrder(TreeNode root){
        if (root == null) {
            return;
        }
        inOrder(root.left);
        System.out.print(root.val+" ");
        inOrder(root.right);
    }



    public String tree2str(TreeNode root){  //力扣606题
        StringBuffer stringBuffer = new StringBuffer();
        tree2strChild(root,stringBuffer);
        return stringBuffer.toString();
    }
    private void tree2strChild(TreeNode t,StringBuffer stringBuffer){
        if (t == null){
            return;
        }
        stringBuffer.append(t.val);
        if (t.left != null){
            stringBuffer.append("(");
            tree2strChild(t.left,stringBuffer);
            stringBuffer.append(")");
        }else {
            if (t.right == null){
                return;
            }else {
                stringBuffer.append("()");
            }
        }
        if (t.right != null){
            stringBuffer.append("(");
            tree2strChild(t.right,stringBuffer);
            stringBuffer.append(")");
        }else {
            return;
        }
    }


    public void preOrderNor(TreeNode root){ //非递归实现前序遍历
        if (root == null){
            return;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode top = null;
        while (cur != null || !stack.isEmpty()){
            while (cur != null){
                stack.push(cur);
                System.out.print(cur.val+" ");
                cur = cur.left;
            }
            top = stack.pop();
            cur = top.right;
        }
    }
}
